import { Button,Table,Image,Input,Modal,Form,Select,message, Upload,Row,Col } from 'antd'
import React from 'react'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'
import { UpdateVarietyActionAsync,LoadVarietyActionAsync } from '../../../redux/action/varietyAction'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import http from '../../../service/http';
const {Search}=Input
const {Option}=Select


const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('你只能上传JPG/PNG的图片!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }

  return isJpgOrPng && isLt2M;
};
function Variety(props) {
  const [page,setPage]=React.useState(1)
  const [showEditVarietyDialog,setShowEditVarietyDialog] = React.useState(false)
  const [selectRow,setSelectRow] = React.useState({})
  const [buttonLoding1,setButtonLoding1] = React.useState({})
  const [buttonLoding2,setButtonLoding2] = React.useState({})
  React.useEffect(()=>{
    props.LoadVarietyActionAsync({pageNum:page})
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
  const columns = [
    {
      title: '菜品编号',
      dataIndex: 'id',
      ellipsis:true,
      align:'center',
    },
    {
      title: '类目',
      dataIndex: 'className',
      ellipsis:true,
      align:'center',
    },
    {
      title: '菜品名称',
      dataIndex: 'name',
      ellipsis:true,
      align:'center',
    },
    {
      title: '菜品图片',
      dataIndex: 'img',
      ellipsis:true,
      align:'center',
      render:(img,row)=>{
        return  <Image width={50} src={img}
          fallback="
          UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJ
          EioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6C
          kYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v
          ///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlk
          lEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/
          ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKI
          AQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSP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HyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
          preview={{
            mask: <span>预览</span>
          }}
      ></Image>
        }
    },
    {
      title: '价格(元)',
      dataIndex: 'price',
      ellipsis:true,
      align:'center',
    },
    {
      title: '单位',
      dataIndex: 'unitName',
      ellipsis:true,
      align:'center',
    },
    {
      title: '月销售',
      dataIndex: 'sum',
      ellipsis:true,
      align:'center',
      render:(sum,row)=>{
        return sum?sum:0 
      }
    },
    {
      dataIndex: 'isShow',
      title:'操作',
      ellipsis:true,
      align:'center',
      render:(isShow,row)=>{
        return(
          <div>
            <Button type='primary' style={{marginRight:'15px'}} onClick={()=>{
              setSelectRow(row)
              setShowEditVarietyDialog(true)
            }}>编辑</Button>
            {
              isShow===1?<Button danger style={{marginRight:'15px'}} loading={buttonLoding1.id===row.id?buttonLoding1.flag:false} onClick={()=>{
              setButtonLoding1({id:row.id,flag:true})
              props.UpdateVarietyActionAsync({...row,isShow:0}).then((res)=>{
                props.LoadVarietyActionAsync({pageNum:page,isLoading:true}).then((data)=>{
                  setButtonLoding1({id:row.id,flag:false})
                  message.success('下架成功！')
                })
              })
            }}>下架</Button>:<Button type='default' style={{marginRight:'15px'}} loading={buttonLoding2.id===row.id?buttonLoding2.flag:false} onClick={()=>{
                setButtonLoding2({id:row.id,flag:true})
              props.UpdateVarietyActionAsync({...row,isShow:1}).then((res)=>{
                props.LoadVarietyActionAsync({pageNum:page}).then((data)=>{
                  setButtonLoding2({id:row.id,flag:false})
                  message.success('上架成功！')
                })
              })
            }}>上架</Button>
            }
          </div>
        )
      }
    }
  ];
  return (
    <div style={{padding:'0 100px'}}>
      <div style={{fontSize:'20px',fontWeight:'800'}}>菜品管理</div>
      <div style={{height:'32px',padding:'16px 0',boxSizing:'content-box'}}>
        <Search placeholder="搜索菜名" onSearch={(e)=>{
          props.LoadVarietyActionAsync({pageNum:page,name:e})
        }} enterButton style={{width:'300px',float:'left'}}/>
        <Button style={{float:'right'}} type='primary' onClick={()=>{
              setSelectRow(null)
              setShowEditVarietyDialog(true)
        }}>添加菜品</Button>
      </div>
      <Table
        dataSource={props.varietyList.list} 
        columns={columns}
        rowKey="id"
        pagination={
          {
            pageSize:8,
            total:props.varietyList.total,
            onChange:(pageNum,pageSize)=>{
              setPage(pageNum)
              props.LoadVarietyActionAsync({pageNum:pageNum,pageSize:pageSize})
            }
          }
        }
        ></Table>
        <UpdateOrAdd 
          visible={showEditVarietyDialog}
          page={page}
          row={selectRow}
          close={()=>{
            setShowEditVarietyDialog(false)
          }}
          props={props}
        />
    </div>
  )
}
//使用connect()()创建并暴露一个Count的容器组件
export default connect(
	state => ({
    varietyList:state.varietyList
	}),
	{UpdateVarietyActionAsync,LoadVarietyActionAsync}
)(Variety)

function UpdateOrAdd(props){
  const [loading, setLoading] = React.useState(false);
  const [imageUrl, setImageUrl] = React.useState(null);
  const [unit,setUnit]=React.useState([])
  const [classList,setClass]=React.useState([])
  const [normList,setNormList]=React.useState([])
  const [fileImg,setFileImg]=React.useState(null)
  const [text,setText]=React.useState('添加菜品')
  const [custom,setCustom]=React.useState(false)
  const [customValue,setCustomValue]=React.useState('')
  const [UpdateOrAddForm]=Form.useForm()
  React.useEffect(() => {
    if(props.visible===true){
      setCustom(false)
      http.getUnit().then((res)=>{
        if(res.code!==200)return
        setUnit(res.data)
      })
      http.getClass().then((res)=>{
        if(res.code!==200)return
        setClass(res.data)
      })
      http.getNorm().then((res)=>{
        if(res.code!==200)return
        setNormList(res.data)
      })
      if(props.row){
        UpdateOrAddForm.setFieldsValue(props.row)
        setImageUrl(props.row.img)
        setText('编辑菜品')
      }
    }else{
      setTimeout(() => {
        UpdateOrAddForm.resetFields()
        UpdateOrAddForm.setFieldsValue({normsType:-1})
        setText('添加菜品')
        setImageUrl(null)
      }, 200);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[props.visible])
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
      });
    }
  };
  const customRequest=(info)=>{
    let reader = new FileReader();
	  reader.readAsDataURL(info.file);
	  reader.onload = function(e) {
		  let fileBase64Data = e.target.result;
      setImageUrl(fileBase64Data)
      setFileImg(info.file)
	  }
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );
  return(
    <Modal
      title={text}
      visible={props.visible}
      forceRender 
      onOk={async ()=>{
        if(imageUrl===null)return message.info('图片不能为空!')
        let fieldsValue = await UpdateOrAddForm.validateFields()
        let objData ={...props.row,...fieldsValue,img:fileImg}
        props.props.UpdateVarietyActionAsync(objData).then((res)=>{
          props.props.LoadVarietyActionAsync({pageNum:props.page})
          props.close()
          if(props.row){message.success('修改成功!')}
          else{message.success('添加成功!')}
        })
      }}
      onCancel={props.close}
      okText='确定'
      cancelText='取消'
      >
      <Form  
        layout="horizontal"
        form={UpdateOrAddForm}
        name="UpdateOrAddForm"
      >
        <Form.Item
          name="classificationId"
          label="菜品类目"
          rules={[
            {
              required: true,
              message: '请输入菜品类目',
            },
          ]}
        >
          <Select
            placeholder="请选择"
            style={{
              width: 160,
            }}
            size='middle'
            // onChange={handleChange}
          >
            {classList.length===0?'':classList.map((item,index)=>{
              return <Option value={item.id} key={item.id}>{item.name}</Option>
            })}
          </Select>
        </Form.Item>
        <Form.Item
          name="name"
          label="菜品名称"
          rules={[
            {
              min:1,
              message: '请输入大于等于1个字符！',
            },
            {
              required: true,
              message: '请输入菜品名称',
            },
          ]}
        >
          <Input placeholder='菜品名称' />
        </Form.Item>
        <Form.Item
          name="price"
          label="菜品价格"
          rules={[
            {
              pattern:/^(([0-9])|([1-9]([0-9]+)))(.[0-9]+)?$/,
              message: '请输入正小数或正整数',
            },
            {
              required: true,
              message: '请输入菜品价格',
            },
          ]}
        >
          <Input placeholder='菜品价格' />
        </Form.Item>
        <Form.Item
          name="unitId"
          label="菜品单位"
          rules={[
            {
              required: true,
              message: '请输入菜品类目',
            },
          ]}
        >
          <Select
            placeholder="请选择"
            style={{
              width: 160,
            }}
            size='middle'
            onChange={(value)=>{
              if(value==='自定义'){
                setCustom(true)
              }else{
                setCustom(false)
              }
            }}
          >
            {unit.length===0?'':unit.map((item,index)=>{
              return <Option value={item.id} key={item.id}>{item.name}</Option>
            })}
            <Option value='自定义' >自定义单位</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="normsType"
          label="菜品规格"
          rules={[
            {
              required: true,
              message: '请输入菜品规格',
            },
          ]}
        >
          <Select
            placeholder="菜品规格"
            style={{
              width: 160,
            }}
            size='middle'
            // onChange={handleChange}
          >
            <Option value={-1}>无</Option>
            {normList.length===0?'':normList.map((item,index)=>{
              return <Option value={item.id} key={item.id}>{item.name}</Option>
            })}
          </Select>
        </Form.Item>
        {
          custom?
            <Row>
              <Col span={12}><Input onChange={(e)=>{
                setCustomValue(e.nativeEvent.data)
              }}></Input></Col>
              <Col span={12}><Button style={{width:'100%'}} type='primary' onClick={()=>{
                if(customValue==='') return message.info('不能为空！')
                http.saveUnit({name:customValue}).then((res1)=>{
                  http.getUnit().then((res)=>{
                    if(res.code!==200)return
                    message.success('添加成功！')
                    setCustomValue('')
                    setCustom(false)
                    setUnit(res.data)
                  })
                })
              }}>添加自定义单位</Button></Col>
            </Row> 
        :null
        }
        <div style={{margin:'10px 0'}}><span style={{color:'red'}}>* </span>菜品图片：点击切换或添加</div>
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChange}
            customRequest={customRequest}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: '100%',
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
      </Form>
    </Modal>
  )
}